<template>
  <Dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    :isModal="false"
    :fullscreen="false"
    :before-close="close"
    width="400px"
    style="border-radius: 10px; box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3)"
  >
    <div class="mt-2 mb-5 text-center" style="font-size: medium"> {{ tipMessage }} </div>
  </Dialog>
</template>
<script setup name="MailReceiveTip" lang="ts">
import { getAccessToken, setToken } from '@/utils/auth'
import { useWebSocket, UseWebSocketReturn } from '@vueuse/core'
import * as MailUtil from '@/views/mailbox/mail/MailUtil'
import { refreshToken } from '@/config/axios/service'
import { useCache, CACHE_KEY } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const message = useMessage() // 消息弹窗
const dialogTitle = ref('收取邮件')
const dialogVisible = ref(false)
const { t } = useI18n() // 国际化
const socketType = 'receive-mail'
/** 发起 WebSocket 连接 */
const socketObject = ref<UseWebSocketReturn<any>>()
const accountIds = ref()
const tipMessage = ref('')

watch(
  () => socketObject.value?.data,
  (data) => {
    if (!data) {
      return
    }
    const receiveData = unref(data)
    try {
      // 1. 收到心跳
      if (receiveData === 'pong') {
        return
      }

      // 2.1 解析 type 消息类型
      const jsonMessage = JSON.parse(receiveData)
      const type = jsonMessage.type
      const content = JSON.parse(jsonMessage.content)
      if (!type) {
        message.error('未知的消息类型：' + data)
        return
      }
      if (type != socketType) return
      if (content.accountName != '') dialogTitle.value = '收取邮件 -' + content.accountName
      if (content.status == 'error') {
        tipMessage.value = '未知错误：' + content.message
        return
      }
      if (
        ['folder_begin', 'folder_done'].includes(content.status) &&
        MailUtil.folderStyle[content.message] != undefined
      ) {
        content.message = t('mailbox.folder.' + content.message)
      }
      if (content.status == 'folder_done') tipMessage.value = '“' + content.message + '”收取完成'
      else if (content.status == 'folder_begin') {
        tipMessage.value = '开始收取' + '“' + content.message + '”'
      } else {
        tipMessage.value = content.message
      }

      if (content.status == 'done') {
        setTimeout(() => {
          close()
        }, 1000)
      }
    } catch (error) {
      message.error('处理消息发生异常：' + data)
      console.error(error)
    }
  }
)
const handlerSend = () => {
  const jsonMessage = JSON.stringify({
    type: socketType,
    content: JSON.stringify(accountIds.value)
  })
  // 2. 最后发送消息
  socketObject.value?.send(jsonMessage)
}

/** 打开弹窗 */
const open = async (params) => {
  dialogVisible.value = true
  tipMessage.value = ''
  const refreshTokenRes = await refreshToken()
  setToken((await refreshTokenRes).data.data)
  socketObject.value = useWebSocket(
    wsCache.get(CACHE_KEY.SERVER_WS_URL) + '?token=' + getAccessToken(),
    {
      autoReconnect: false,
      heartbeat: false
    }
  )
  accountIds.value = params
  handlerSend()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const emit = defineEmits(['close'])

/** 关闭弹窗 */
const close = async () => {
  if (unref(socketObject.value?.status) === 'OPEN') socketObject.value?.close()
  dialogVisible.value = false
  emit('close', accountIds.value)
}
</script>
